Creating maintainable JavaScript code is important if want to keep using the code.
In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at avoiding global variables.
Avoid Globals
JavaScript’s execution environment is unique in that we used to use lots o global variables and functions.
The default execution environment of JavaScript is to use global variables everywhere.
Everything we have is defined as properties of the global object.
It’s an object that represents the outermost context for a script.
The window
is the global object in the browser.
So any variable or function declared in the global scope becomes the property of the window
object.
For instance, we have:
var color = "red"
or
function getColor() {
console.log(color);
}
Then we can get the values by using:
console.log(window.color)
or:
window.getColor();
However, it’s a bad practice to create global variables everywhere since they have many issues.
One issue that it has is naming collisions.
Since everything is in the same scope, it’s likely that we have naming collisions within the global scope.
We may have defined the color
global variable somewhere else.
This will overwrite the value of the one that’s defined earlier.
The getColor
variable depends on color
, so it would hard to track down the actual value of color
.
We don’t know where color
comes from.
Also, we run the risk that the global variable may become a built-in browser global variable later on.
Code Fragility
Having global variables makes the code tightly coupled to the environment.
If the environment changes, then the function is likely to break.
The getColor
method logs undefined
if the color
variable no longer exists.
This means that any change to the global environment is capable of causing errors throughout the code.
Globals can be changed at any point by any function.
This means the reliability of global variables is also suspect.
To make our code more robust, we should avoid global variables.
So we instead of logging color
directly in our getColor
function, we should log the color
from a parameter instead.
For instance, we can write:
function getColor(color) {
console.log(color);
}
to get the color
from a parameter instead.
This way, we know where it comes from.
Difficulty Testing
Having global variables also makes our code hard to tests.
Creating tests is very difficult if they rely on global variables since they can be changed by anything.
The tight coupling between different parts of the code caused by global variables causes unpredictable results.
Therefore, we got to fix this by removing the dependency on global variables.
We shouldn’t create our own global variables.
But we can rely on globals that are native to JavaScript like Array
or Date
.
Conclusion
We should avoid global variables as much as we can.
They make our code hard to test.
And the code that we create is fragile since the global variables can be changed anywhere by anything.